import editForm from "../form.vue";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import type { FormItemProps } from "../utils/types";
import type { PaginationProps } from "@pureadmin/table";
import {
  cloneDeep,
  deviceDetection,
  getKeyList,
  isAllEmpty
} from "@pureadmin/utils";
import { h, onMounted, reactive, type Ref, ref, toRaw, watch } from "vue";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";

export function useRole(treeRef: Ref) {
  const form = reactive({
    name: "",
    code: "",
    status: ""
  });
  const curRow = ref();
  const formRef = ref();
  const dataList = ref([]);
  const treeIds = ref([]);
  const treeData = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const isLinkage = ref(true);
  const treeSearchValue = ref();
  const switchLoadMap = ref({});
  const isExpandAll = ref(false);
  const isSelectAll = ref(false);
  const { switchStyle } = usePublicHooks();
  const cloneMenuList = ref([]); //菜单栏列表数据
  const treeProps = {
    value: "Id",
    label: "Title",
    children: "children"
  };
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "角色编号",
      prop: "Id"
    },
    {
      label: "角色名称",
      prop: "Name"
    },
    {
      label: "角色标识",
      prop: "Code"
    },
    {
      label: "状态",
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.Status}
          disabled={scope.row.Code === "superadmin"}
          active-value={true}
          inactive-value={false}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      ),
      minWidth: 90
    },
    {
      label: "备注",
      prop: "Remark",
      minWidth: 160
    },
    {
      label: "编辑时间",
      prop: "UpdatedAt",
      minWidth: 160
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        !row.Status ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.Name
      }</strong>吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        http
          .post(changeHttpLink("/api/System/change_role_status"), {
            data: {
              listIds: [row.Id],
              status: row.Status ? 1 : 0
            }
          })
          .then((res: any) => {
            if (res.Success) {
              message(`已${!row.Status ? "停用" : "启用"}${row.Name}`, {
                type: "success"
              });
              onSearch();
            } else {
              !row.Status ? (row.Status = true) : (row.Status = false);
              message(res.Message, { type: "error" });
            }
            switchLoadMap.value[index] = Object.assign(
              {},
              switchLoadMap.value[index],
              {
                loading: false
              }
            );
            loading.value = false;
          })
          .catch(err => {
            !row.Status ? (row.Status = true) : (row.Status = false);
            message(err.message, { type: "error" });
          });
      })
      .catch(() => {
        !row.Status ? (row.Status = true) : (row.Status = false);
      });
  }

  function handleDelete(row) {
    http
      .post(changeHttpLink("/api/System/role_remove"), {
        data: {
          listIds: [row.Id]
        }
      })
      .then((res: any) => {
        if (res.Success) {
          message(`您删除了角色名称为${row.Name}的这条数据`, {
            type: "success"
          });
          onSearch();
        } else {
          message(res.Message, { type: "error" });
        }
        loading.value = false;
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }

  function handleSizeChange(val: number) {
    pagination.currentPage = 1;
    pagination.pageSize = val;
    dataList.value = [];
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  async function onSearch() {
    const searchLimit = toRaw(form);
    const paginationInfo = toRaw(pagination);
    loading.value = true;
    const params: any = {
      Name: searchLimit.name ?? "",
      Status: !isAllEmpty(form.status) ? form.status : -1,
      Code: searchLimit.code ?? "",
      PageIndex: paginationInfo.currentPage,
      PageSize: paginationInfo.pageSize
    };

    http
      .post(changeHttpLink("/api/System/role_list"), { data: params })
      .then((res: any) => {
        // 返回格式要求：唯一id加父节点parentId，parentId取父节点id
        if (res.Data != null) {
          dataList.value = res.Data.Items;
          pagination.total = res.Data.TotalCount;
        }
        setTimeout(() => {
          loading.value = false;
        }, 300);
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row: any) {
    addDialog({
      title: `${title}角色`,
      props: {
        formInline: {
          id: row?.Id ?? 0,
          name: row?.Name ?? "",
          code: row?.Code ?? "",
          remark: row?.Remark ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;

        function chores() {
          message(`您${title}了角色名称为${curData.name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }

        FormRef.validate(valid => {
          if (valid) {
            loading.value = true;
            const formData = {
              Id: 0,
              Name: curData?.name ?? "",
              Code: curData?.code ?? "",
              Remark: curData?.remark ?? ""
            };
            if (title !== "新增") {
              formData.Id = curData.id;
            }
            http
              .post(changeHttpLink("/api/System/role_edit"), {
                data: formData
              })
              .then((res: any) => {
                if (res.Success) {
                  chores();
                } else {
                  message(res.Message, { type: "error" });
                }
                loading.value = false;
              })
              .catch(err => {
                loading.value = false;
                message(err.message, { type: "error" });
              });
          }
        });
      }
    });
  }

  /** 菜单权限 */
  async function handleMenu(row?: any) {
    const { Id } = row;
    if (Id) {
      curRow.value = row;
      isShow.value = true;
      loading.value = true;
      http
        .get(changeHttpLink("/api/System/role_menu_ids"), {
          params: { roleId: Id }
        })
        .then((res: any) => {
          if (res.Data != null) {
            const listIds = res.Data.map(item => {
              return item.MenuId;
            });
            treeRef.value.setCheckedKeys(listIds);
          }
          loading.value = false;
        })
        .catch(err => {
          loading.value = false;
          message(err.message, { type: "error" });
        });
    } else {
      curRow.value = null;
      isShow.value = false;
    }
  }

  /** 高亮当前权限选中行 */
  function rowStyle({ row: { Id } }) {
    return {
      cursor: "pointer",
      background: Id === curRow.value?.Id ? "var(--el-fill-color-light)" : ""
    };
  }

  /** 递归方式查询上级数据 */
  function findAncestors(menuData, targetId) {
    const ancestors = [];

    function findParent(currentId) {
      const parent = menuData.find(item => item.Id === currentId);
      if (parent) {
        ancestors.push(parent);
        if (parent.ParentId !== 0) {
          findParent(parent.ParentId);
        }
      }
    }

    findParent(menuData.find(item => item.Id === targetId).ParentId);

    return ancestors.reverse(); // 反转数组，使上级在前
  }

  /** 菜单权限-保存 */
  function handleSave() {
    const { Id, Name } = curRow.value;
    const listIds = treeRef.value.getCheckedKeys();
    let listData = cloneMenuList.value
      .filter(x => {
        if (listIds.indexOf(x.Id) > -1) {
          return x;
        }
      })
      .map(item => {
        return {
          MenuId: item.Id,
          MenuType: item.MenuType,
          IsChecked: true
        };
      });
    const lastDealData = cloneDeep(listData);
    const listHasAddIds = cloneDeep(listIds);

    for (const item of lastDealData) {
      let listTempData = findAncestors(cloneMenuList.value, item.MenuId);
      listTempData = listTempData
        .filter(x => {
          if (!listHasAddIds.includes(x.Id)) {
            return x;
          }
        })
        .map(item => {
          listHasAddIds.push(item.id);
          return {
            MenuId: item.Id,
            MenuType: item.MenuType,
            IsChecked: false
          };
        });

      listData = [...listTempData, ...listData];
    }
    const formData = {
      RoleId: Id,
      RolePermissions: listData
    };
    http
      .post(changeHttpLink("/api/System/save_permission"), {
        data: formData
      })
      .then((res: any) => {
        if (res.Success) {
          message(`角色名称为${Name}的菜单权限修改成功`, {
            type: "success"
          });
        } else {
          message(res.Message, { type: "error" });
        }
        loading.value = false;
      })
      .catch(err => {
        loading.value = false;
        message(err.message, { type: "error" });
      });
  }

  const onQueryChanged = (query: string) => {
    treeRef.value!.filter(query);
  };

  const filterMethod = (query: string, node) => {
    return node.title!.includes(query);
  };

  onMounted(async () => {
    onSearch();
    getMenuList();
  });

  const getMenuList = () => {
    http
      .get(changeHttpLink("/api/System/menu_list"))
      .then((res: any) => {
        // 返回格式要求：唯一id加父节点parentId，parentId取父节点id
        if (res.Data != null) {
          const newData = res.Data;
          cloneMenuList.value = cloneDeep(newData);
          treeIds.value = getKeyList(newData, "Id");
          treeData.value = handleTree(newData, "Id", "ParentId"); // 处理成树结构
        }
      })
      .catch(err => {
        message(err.message, { type: "error" });
      });
  };

  watch(isExpandAll, val => {
    val
      ? treeRef.value.setExpandedKeys(treeIds.value)
      : treeRef.value.setExpandedKeys([]);
  });

  watch(isSelectAll, val => {
    val
      ? treeRef.value.setCheckedKeys(treeIds.value)
      : treeRef.value.setCheckedKeys([]);
  });

  return {
    form,
    isShow,
    curRow,
    loading,
    columns,
    rowStyle,
    dataList,
    treeData,
    treeProps,
    isLinkage,
    pagination,
    isExpandAll,
    isSelectAll,
    treeSearchValue,
    onSearch,
    resetForm,
    openDialog,
    handleMenu,
    handleSave,
    handleDelete,
    filterMethod,
    onQueryChanged,
    handleSizeChange,
    handleCurrentChange
  };
}
